//
//  AppDelegate.m
//  gungunchou
//
//  Created by LJJ on 2017/9/22.
//  Copyright © 2017年 xskj. All rights reserved.
//  测试账号18623640502  123456a

#import "AppDelegate.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "UMessage.h"
#import "UMMobClick/MobClick.h"
#import "HomeViewController.h"
#import "UpdateNoticeView.h"
#import "InitViewController.h"
#import "LaunchNoNetController.h"
#import "BaseTabbarCon.h"

@interface AppDelegate () <UIAlertViewDelegate,UNUserNotificationCenterDelegate,UIApplicationDelegate>
@property (nonatomic, strong) UIAlertView *verAlert;
@property (nonatomic, strong) UpdateNoticeView *verUpdateAlert;//版本更新提示view

@property (nonatomic, assign) NSInteger isFoecedUpdate;         //是否强制更新
@property (nonatomic, copy) NSString *downloadURL;              //更新地址
@property (nonatomic, assign) NSInteger isNeedUpdate;           //是否可以更新

@property (nonatomic, strong) NSDictionary *launchOptions;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];//因为初始加载launchScreen隐藏了,这里重新显示出来
    
    //推送消息payload
    NSDictionary *payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"UMPushInfoDic"];
    if (payload) {
        NSDictionary *ext = [payload objectForKey:@"ext"];
        if (ext) {
            [[NSUserDefaults standardUserDefaults] setObject:ext forKey:@"UMPushInfoDic"];
        }
    }
    
    self.launchOptions = launchOptions;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    //    self.waitView = [[WaitViewController alloc]init];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    [self.window makeKeyAndVisible];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"InitLk"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(configThirds) name:App_Config_Thirds object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initPage) name:App_InitPage object:nil];
    
    [self configInitCon];
    
    [self configThirds];
    
    //initpage
    [self initPage];
    
    //检查版本更新
//    [self checkVersion];
    
    
    return YES;
}

- (void)configThirds
{
    //友盟统计配置
    [self umengAnalyticscConfig];
    
    //友盟分享配置
    [self umengShare];
    
    //友盟推送配置
    [self umengPushTrack:self.launchOptions];
}

- (void)configRootCon
{
    HomeViewController *home = [[HomeViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:home];
    self.window.rootViewController = nav;
}

//原生页面
- (void)configTestAppRootCon
{
    BaseTabbarCon *tabCon = [[BaseTabbarCon alloc] init];
    self.window.rootViewController = tabCon;
}

- (void)configNoNetRootCon
{
    LaunchNoNetController *con = LaunchNoNetController.new;
    self.window.rootViewController = con;
}

- (void)configInitCon
{
    InitViewController *initCon = [[InitViewController alloc] init];
    self.window.rootViewController = initCon;
}

- (void)initPage
{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:app_Version,@"param1",@"2",@"param2", nil];
    NSString *urlLinkApi = [NSString stringWithFormat:@"%@?param1=%@&param2=2",InitPageUrl,app_Version];
    
    [[CGNetManage shared] httpInitPageWithUrlLink:urlLinkApi Completed:^(NSDictionary *response) {
        NSString *content1 = [response objectForKey:@"content1"];
        NSString *content2 = [response objectForKey:@"content2"];
        NSString *type = [response objectForKey:@"opentype"];
        
        NSString *initLinkUrl = DefaultLk;
        if ([content1 isKindOfClass:[NSNull class]]) {
            
        }
        else {
            if (content1 && ![content1 isEqualToString:@""]) {
                initLinkUrl = content1;
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:initLinkUrl forKey:@"InitLk"];
        
        
        if (type && type.integerValue == 1) {
            [self configRootCon];//原逻辑
        }
        else {
            [self configTestAppRootCon];//测试进原生页用
        }
        
        
//        [self configTestAppRootCon];//测试进原生页用
        
//        [self configRootCon];//原逻辑
        
        
        if (content2) {
            if (content2.integerValue == 1) {
                [self checkVersion];
            }
        }
        
    } fail:^(NSError *err) {
        
        [self configNoNetRootCon];
    }];
}

- (void)forTest
{
    NSString *t = @"";
}

- (void)umengAnalyticscConfig
{
    UMConfigInstance.appKey = UM_APPKEY;
    UMConfigInstance.channelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
}


 - (void)umengShare{
     [[UMSocialManager defaultManager] openLog:YES];
     
     [[UMSocialManager defaultManager] setUmSocialAppkey:UM_APPKEY];
     
     //出现报错2014，由于ATS的原因，所有HTTP链接在SDK内都被禁止，并提示错误告知非https图片不可分享，请使用https图片
     //如果一定要使用http图片，请在APPdelegate.m中添加下列代码：
     [UMSocialGlobal shareInstance].isUsingHttpsWhenShareContent = NO;
     
     [self configUSharePlatforms];
     
     //[self confitUShareSettings];
 }

- (void)configUSharePlatforms{

    /* 设置weixin的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WXAppKey  appSecret:WXAppSecret redirectURL:WXRedirect];
    
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:WXAppKey  appSecret:WXAppSecret redirectURL:WXRedirect];

    /* 设置qq的appKey和appSecret */
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey appSecret:QQAppSecret redirectURL:QQRedirect];

    //暂时不要新浪了!!!
    /* 设置sina的appKey和UrlString */
//    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:SinaAppKey appSecret:SinaAppSecret redirectURL:SinaRedirect];
}

////9.6  解决微博(完整版)webview回调的崩溃,未安装新浪微博客户端时会弹出Webview进行登录和分享，之后会回调至以下函数:
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return YES;
//}

// 支持所有iOS系统
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

//仅支持iOS9以上系统，iOS8及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    //6.3的新的API调用，是为了兼容国外平台(例如:新版facebookSDK,VK等)的调用[如果用6.2的api调用会没有回调],对国内平台没有影响
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

//友盟推送 -----------------------
- (void)umengPushTrack:(NSDictionary *)launchOptions{
    [UMessage startWithAppkey:UM_APPKEY launchOptions:launchOptions httpsenable:YES ];
    //    [UMessage startWithAppkey:USHARE_DEMO_APPKEY launchOptions:launchOptions];
    [UMessage registerForRemoteNotifications];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    [UMessage setLogEnabled:YES];
    [MobClick setLogEnabled:YES];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
    
//    [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (deviceToken) {
        [UMessage registerDeviceToken:deviceToken];
    }
    [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"deviceToken"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
//    NSDictionary *ext = [userInfo objectForKey:@"ext"];
//    [UMessage didReceiveRemoteNotification:userInfo];
//    if (ext) {
//        [[NSUserDefaults standardUserDefaults] setObject:ext forKey:@"UMPushInfoDic"];
//    }
//}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    
    NSDictionary *ext = [userInfo objectForKey:@"ext"];
    [UMessage didReceiveRemoteNotification:userInfo];
    if (ext) {
        [[NSUserDefaults standardUserDefaults] setObject:ext forKey:@"UMPushInfoDic"];
    }
    completionHandler(UIBackgroundFetchResultNewData);
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //关闭U-Push自带的弹出框
        [UMessage setAutoAlert:NO];
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//点击通知
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    NSDictionary *ext = [userInfo objectForKey:@"ext"];
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {

        [UMessage didReceiveRemoteNotification:userInfo];
        if (ext) {
            [[NSUserDefaults standardUserDefaults] setObject:ext forKey:@"UMPushInfoDic"];
            if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {//前台点击
                [NotificationCenter postNotificationName:Foreground_Push_Get object:ext];
            }
        }
        
    }else{
        
    }
    completionHandler();  // 系统要求执行这个方法
}


//检查版本
- (void)checkVersion{
    if ([CGNetManage isReachable] == YES) {
        [NotificationCenter addObserver:self selector:@selector(closeUpdateNotice) name:CloseUpdateNotice object:nil];
        
        NSString *localVer = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        NSString *buildVer = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleVersion"];
//        NSDictionary *params=[[NSDictionary alloc]initWithObjectsAndKeys:localVer,@"versioName",buildVer,@"versionCode", nil];
    
        [[CGNetManage shared] httpCheckVersionWithCompleted:^(NSDictionary *verDic) {
            if (verDic) {
                self.isFoecedUpdate = [[verDic objectForKey:@"IsMustUpdate"] integerValue];
                self.isNeedUpdate = [[verDic objectForKey:@"IsNeedUpdate"] integerValue];
                self.downloadURL = [verDic objectForKey:@"DownloadUrl"];
                if (!self.downloadURL) {
                    self.downloadURL = BaseURL;//若没有弄个首页默认
                }
                NSString *currentVer = [verDic objectForKey:@"Version"];
                NSString *content = [verDic objectForKey:@"Content"];
                content = [NSString stringWithFormat:@"%@",[content stringByReplacingOccurrencesOfString:@"\\n" withString:@" \r\n" ]];//处理换行符
                
                if ([NSString isNullOrEmpty:content]) {
                    content = [NSString stringWithFormat:@"有新版本v%@可以更新,你想要更新吗？",currentVer];
                }
                NSComparisonResult compareResult = [localVer compare:currentVer];
                if (compareResult == NSOrderedAscending) {//如果当前本地安装的版本号小于服务器获取到的版本号 就需要更新
                    NSString *cancelBtnTitle = @"取消";
                    if (self.isFoecedUpdate > 0) {//强制更新
                        cancelBtnTitle = @"退出";
                    }
//                    self.verAlert = [[UIAlertView alloc] initWithTitle:@"版本更新" message:content delegate:self cancelButtonTitle:cancelBtnTitle otherButtonTitles:@"更新", nil];
//                    self.verAlert.tag = 22222;
//                    [self.verAlert show];

                    [self alertVerUpdateViewWithCancelTitle:cancelBtnTitle updateUrl:self.downloadURL content:content];
                }
            }
        } fail:^(NSError *error) {
            
        }];
    }
}

- (void)alertVerUpdateViewWithCancelTitle:(NSString *)cencelTitle updateUrl:(NSString *)updateUrl content:(NSString *)content
{
    [LJUtility addMaskViewOnWindow];
    self.verUpdateAlert = [[NSBundle mainBundle] loadNibNamed:@"UpdateNoticeView" owner:nil options:nil].firstObject;
    self.verUpdateAlert.frame = CGRectMake(0, SCREEN_HEIGHT/2-150, SCREEN_WIDTH, 300);
    [self.verUpdateAlert.cancelBtn setTitle:cencelTitle forState:UIControlStateNormal];
    self.verUpdateAlert.updateUrl = updateUrl;
    self.verUpdateAlert.contentTextV.text = content;
    [KWindow addSubview:self.verUpdateAlert];
}

- (void)closeUpdateNotice
{
    [self.verUpdateAlert removeFromSuperview];
    self.verUpdateAlert = nil;
    [LJUtility dismissMaskViewFromWindow];
}

#pragma mark - alertview代理
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    switch (buttonIndex) {
        case 0:
        {
            if (alertView.tag == 22222 && self.isFoecedUpdate > 0) {
                [self exitApp];
            }
            break;
        }
            
        case 1:
        {
            if (alertView.tag == 22222) {
                //进入appstore更新
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:self.downloadURL]];//服务器提供appstore更新地址
                [self exitApp];
            }
            break;
        }
            
        default:
            break;
    }
}


//退出应用
- (void)exitApp {
    UIWindow *window = self.window;
    [UIView animateWithDuration:0.5f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0,SCREEN_HEIGHT/2, SCREEN_WIDTH, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
}


- (void)intoHomeApp{
    HomeViewController *home = [[HomeViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:home];
    APPDelegete.window.rootViewController = nav;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:deviceToken ,@"ServiceID", nil];
    [[CGNetManage shared] httpPost:[CGUrlManage getSetThreadKillUrl] params:params completed:^(NSString *resultMessage, id data) {
        
    } failed:^(NSString *resultcode, id data) {
        
    } error:^(id data) {
        
    }];
    //    long long i = 0;
    //    while (1) {
    //        i++;
    //        NSLog(@"i = %lld",i);
    //    }
    [NSThread sleepForTimeInterval:2];
}


@end
